package cn.iocoder.yudao.module.digital.convert;

import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserIdsConverter implements Converter<String> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                GlobalConfiguration globalConfiguration) {
        throw new UnsupportedOperationException("暂不支持导入");
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
                                           GlobalConfiguration globalConfiguration) {
        if (!StringUtils.hasText(value)) {
            return new WriteCellData<>("");
        }
        
        try {
            // 将逗号分隔的ID字符串转换为Long列表
            List<Long> userIds = Arrays.stream(value.split(","))
                                     .map(String::trim)
                                     .filter(StringUtils::hasText)
                                     .map(Long::valueOf)
                                     .collect(Collectors.toList());
            
            if (userIds.isEmpty()) {
                return new WriteCellData<>(value);
            }
            
            // 使用 UserNameConverter 转换每个用户ID
            List<String> userNames = userIds.stream()
                    .map(id -> {
                        WriteCellData<?> cellData = new UserNameConverter().convertToExcelData(String.valueOf(id), 
                            contentProperty, globalConfiguration);
                        return cellData.getStringValue();
                    })
                    .collect(Collectors.toList());
            
            // 返回逗号分隔的用户名字符串
            return new WriteCellData<>(String.join(", ", userNames));
        } catch (NumberFormatException e) {
            // 如果转换失败，直接返回原值
            return new WriteCellData<>(value);
        }
    }
}
